/*
 * @Date: 2022-05-20 12:46:49
 * @LastEditors: sailornpg
 * @LastEditTime: 2022-05-21 17:52:36
 * @FilePath: \my-react-components\src\component\Menu\subMenu.tsx
 * @Description: subMenu
 */
import classNames from "classnames";
import React, {
  FunctionComponentElement,
  memo,
  useContext,
  useState,
} from "react";
import { menuContext } from ".";
import Transition from "../Transition";
import { MenuItemProps } from "./MenuItem";
import Icon from "../Icon";
export interface SubMenuProps {
  index?: string;
  title: string;
  className?: string;
  children?: React.ReactNode;
}
const SubMenu: React.FC<SubMenuProps> = memo(
  ({ children, index, title, className }) => {
    const context = useContext(menuContext);
    const openSubMenu = context.defalutOpenSubMenu as string[];
    const isOpend =
      index && context.mode === "vertical"
        ? openSubMenu.includes(index)
        : false;
    const [opend, setOpend] = useState(isOpend);
    const subMenuOpend = classNames("sailor-submenu", {
      "menu-opend": opend,
    });
    const classes = classNames("menu-item submenu-item", className, {
      "is-active": context.index === index,
      "is-vertical": context.mode === "vertical",
      "is-opened": opend,
    });
    const handleClick = (e: React.MouseEvent) => {
      e.preventDefault();
      setOpend(!opend);
    };
    let timer;
    const handleMouse = (e: React.MouseEvent, toggle: boolean) => {
      clearTimeout(timer);
      e.preventDefault();
      timer = setTimeout(() => {
        setOpend(toggle);
      }, 300);
    };
    const clickEvents =
      context.mode === "vertical"
        ? {
            onClick: handleClick,
          }
        : {};
    const hoverEvents =
      context.mode !== "vertical"
        ? {
            onMouseEnter: (e: React.MouseEvent) => {
              handleMouse(e, true);
            },
            onMouseLeave: (e: React.MouseEvent) => {
              handleMouse(e, false);
            },
          }
        : {};
    const renderChildren = () => {
      const childrenCMP = React.Children.map(children, (child, i) => {
        const childrenEl = child as FunctionComponentElement<MenuItemProps>;
        const { displayName } = childrenEl.type;
        if (displayName === "MenuItem") {
          return React.cloneElement(childrenEl, {
            index: `${index}-${i}`,
          });
        } else {
          console.error("在subMenu组件中子组件只能使用'MenuItem'");
        }
      });
      return (
        <Transition in={opend} timeout={300} classNames="zoom-in-top">
          <ul className={subMenuOpend}>{childrenCMP}</ul>
        </Transition>
      );
    };
    return (
      <li key={index} className={classes} {...hoverEvents}>
        <div className="submenu-title" {...clickEvents}>
          {title}
          <Icon icon="angle-down" className="arrow-icon"></Icon>
        </div>
        {renderChildren()}
      </li>
    );
  },
);
SubMenu.displayName = "SubMenu";
export default SubMenu;
